package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.dao.SkuInfoDao;
import com.atguigu.gulimall.product.entity.SkuImagesEntity;
import com.atguigu.gulimall.product.entity.SkuInfoEntity;
import com.atguigu.gulimall.product.entity.SpuInfoDescEntity;
import com.atguigu.gulimall.product.entity.SpuInfoEntity;
import com.atguigu.gulimall.product.feign.SeckillFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.AttrGroupWithAttrsVo;
import com.atguigu.gulimall.product.vo.SecKillSkuVo;
import com.atguigu.gulimall.product.vo.SkuItemVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.netty.util.concurrent.CompleteFuture;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private SkuSaleAttrValueService saleAttrValueService;
    @Autowired
    private ThreadPoolExecutor executor;

    @Autowired
    private SeckillFeignService seckillFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfo) {
        this.save(skuInfo);
    }

    @Override
    public PageUtils queryByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<SkuInfoEntity>();

        String key = (String) params.get("key");
        if(StringUtils.isNotEmpty(key)){
            wrapper.and(e->{
                e.eq("id",key).or().like("spu_name",key);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if(StringUtils.isNotEmpty(catelogId)&&!catelogId.equals("0")){
            wrapper.eq("catalog_id",catelogId);
        }

        String brandId = (String) params.get("brandId");
        if(StringUtils.isNotEmpty(brandId)&&!brandId.equals("0")){
            wrapper.eq("brand_id",brandId);

        }

        String min = (String) params.get("min");
        if(StringUtils.isNotEmpty(min)){
            wrapper.ge("price",min);

        }
        String max = (String) params.get("max");
        if(StringUtils.isNotEmpty(min)){
            wrapper.le("price",max);

        }
        //key: '华为',//检索关键字
        //        catelogId: 0,
        //        brandId: 0,
        //        min: 0,
        //        max: 0
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params), wrapper
        );



        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        List<SkuInfoEntity> list = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return list;
    }

    @Override
    public SkuItemVo item(Long skuId) {
        SkuItemVo skuItemVo = new SkuItemVo();

        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            //1.sku基本信息
            SkuInfoEntity info = this.getById(skuId);
            skuItemVo.setInfo(info);
            return info;
        }, executor);

        CompletableFuture<Void> attrValueFuture = infoFuture.thenAcceptAsync((res) -> {
            //3.spu销售组合信息
            List<SkuItemVo.SkuItemSaleAttrVo> saleAttr=saleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            skuItemVo.setSaleAttr(saleAttr);
        }, executor);


        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync((res) -> {
            //4.spu介绍
            SpuInfoDescEntity infoDesc = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setDesp(infoDesc);
        }, executor);


        CompletableFuture<Void> attrGroupFuture = infoFuture.thenAcceptAsync((res) -> {
            //5.spu规格参数
            List<SkuItemVo.SpuItemGroupVo> groupAttr=attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(),res.getCatalogId());
            skuItemVo.setGroupAttr(groupAttr);
        }, executor);

        CompletableFuture<Void> imgFuture = CompletableFuture.runAsync(() -> {
            //2.sku图片信息
            List<SkuImagesEntity> skuImages = skuImagesService.getImageBySkuId(skuId);
            skuItemVo.setImages(skuImages);
        }, executor);

        CompletableFuture<Void> seckillSkuFuture = CompletableFuture.runAsync(() -> {
            //6.查询当前商品是否参与秒杀活动
            R skuSeckillInfo = seckillFeignService.getSkuSeckillInfo(skuId);
            Integer code = skuSeckillInfo.getCode();
            if (code == 0) {
                SecKillSkuVo secKillSkuVo = skuSeckillInfo.getData(new TypeReference<SecKillSkuVo>() {
                });
                if (secKillSkuVo != null) {
                    skuItemVo.setSecKillSkuVo(secKillSkuVo);
                }
            }
        });


        //组合
        try {
            CompletableFuture.allOf(attrValueFuture,descFuture,attrGroupFuture,imgFuture,seckillSkuFuture).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        return skuItemVo;
    }

    @Override
    public List<String> getAttrValues(Long skuId) {
        List<String> attrValues=this.baseMapper.getAttrValues(skuId);
        return attrValues;
    }

}